package com.reflectdemo;

import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

import com.library.UserInit;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        UserInit.initName();
        testReflect();
    }

    private void testReflect() {
        try {
            Class c = Class.forName("com.reflectdemo.UserInfo");
            UserInfo info = (UserInfo) c.newInstance();
            Method[] methods = c.getDeclaredMethods();
            for (int i = 0; i < methods.length; i++) {
                methods[i].setAccessible(true);
                if (methods[i].getName().equals("setName")) {
                    methods[i].invoke(info, "Gerry_Jie");
                }
                if (methods[i].getName().equals("getName")) {
                    methods[i].invoke(info);
                }
            }

            Field[] fields = c.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                fields[i].setAccessible(true);
                fields[i].set(info,"Gerry_Jie2");
            }

            for (int i = 0; i < methods.length; i++) {
                methods[i].setAccessible(true);
                if (methods[i].getName().equals("getName")) {
                    methods[i].invoke(info);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.i("TAG", "testReflect: " + e.getMessage());
        }
    }
}